using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TanashCMS.Business;
using TanashCMS.Business.Task;
using TanashCMS.Business.Utility;

public partial class manager_inventory_AddUpdateProduct : CMSManagementPageBase
{
    private Product mProduct = null;
    private int mSavedProductID { get { return ViewState["savedProductID"] != null ? (int)ViewState["savedProductID"] : 0; } set { ViewState["savedProductID"] = value; } }
    protected int _productId { get { return Request.QueryString["id"] != null ? int.Parse(Request.QueryString["id"]) : 0; } }
    protected int _viewingCategoryId { get { return Request.QueryString["lastCid"] != null ? int.Parse(Request.QueryString["lastCid"]) : 0; } } 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            DataBind();
    }

    protected override void OnInit(EventArgs e)
    {
        if (_productId != 0) mProduct = Product.Get(_productId);

        base.OnInit(e);
    }

    public override void DataBind()
    {
        if (mProduct != null)
        {
            txtProductTitle.Text = mProduct.Title;
            txtSearchKeywords.Text = mProduct.SearchKeywords;
            fckProductDetails.Value = mProduct.HTMLContent;
            txtUPC.Text = mProduct.UPC;
            txtPrice.Text = string.Format("{0:0.00}", mProduct.Price);
            txtDiscount.Text = string.Format("{0:0.00}", mProduct.Discount);
            productImage.ImageUrl = "/services/thumbnail.aspx?method=restricttosize&sx=400&i=" + mWebsite.ImagesFolder + "/" + HttpUtility.UrlPathEncode(mProduct.PhotoURL);
            hiddenImageUrl.Value = mProduct.PhotoURL;
            fieldSelectedCategoryId.Value = mProduct.CategoryID.ToString();
        }
        base.DataBind();
    }

    protected void tvCategories_DataBinding(object sender, EventArgs e)
    {
        tvCategories.Nodes.Clear();
        IList<Category> cats = new InventoryTask(mWebsite.ID).GetCategories(0);
        foreach (Category cat in cats)
        {
            TreeNode node = new TreeNode();
            node.Text = cat.Title;
            node.Value = cat.ID.ToString();

            if (mProduct != null)
            {
                if (cat.ID == mProduct.CategoryID)
                    node.Select();
            }
            else if (!IsPostBack)
                if (_viewingCategoryId == cat.ID)
                    node.Select();

            BindChildNodes(node);
            tvCategories.Nodes.Add(node);
            node.Expand();
        }
        tvCategories.ExpandAll();

    }

    private void BindChildNodes(TreeNode ParentNode)
    {
        IList<Category> cats = new InventoryTask(mWebsite.ID).GetCategories(int.Parse(ParentNode.Value));
        foreach (Category cat in cats)
        {
            TreeNode node = new TreeNode();
            node.Text = cat.Title;
            node.Value = cat.ID.ToString();

            if (mProduct != null)
            {
                if (cat.ID == mProduct.CategoryID)
                    node.Select();
            }
            else if (!IsPostBack)
                if (_viewingCategoryId == cat.ID)
                    node.Select();

            BindChildNodes(node);
            ParentNode.ChildNodes.Add(node);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Page.Validate();
        if (!Page.IsValid)
            return;

        string imageUrl = hiddenImageUrl.Value.Replace(mWebsite.ImagesFolder, "");

        if (_productId != 0)
        {
            new InventoryTask(mWebsite.ID).UpdateProduct(_productId, int.Parse(fieldSelectedCategoryId.Value), txtUPC.Text, txtProductTitle.Text,
                fckProductDetails.Value, imageUrl, double.Parse(txtPrice.Text), double.Parse(txtDiscount.Text), "default", txtSearchKeywords.Text, User.Identity.Name);

            productImage.ImageUrl = "/services/thumbnail.aspx?method=restricttosize&sx=400&i=" + mWebsite.ImagesFolder + HttpUtility.UrlPathEncode(hiddenImageUrl.Value);
        }
        else
        {
            int newProductId = new InventoryTask(mWebsite.ID).CreateProduct(int.Parse(fieldSelectedCategoryId.Value), txtUPC.Text, txtProductTitle.Text, fckProductDetails.Value,
                imageUrl, double.Parse(txtPrice.Text), double.Parse(txtDiscount.Text), "default", txtSearchKeywords.Text, User.Identity.Name);

            Response.Redirect("AddUpdateProduct.aspx?id=" + newProductId.ToString() + "&lastCid=" + _viewingCategoryId);
        }
    }


    protected void odsProductOptions_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        if (mWebsite != null)
            e.InputParameters["WebsiteID"] = mWebsite.ID;
    }
    protected void gvProductOptions_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ProductOptionType optionType = (ProductOptionType)e.Row.DataItem;
            if (optionType != null)
            {
                TextBox txtValue = (TextBox)e.Row.FindControl("txtOptionValue");


                if (mProduct != null && txtValue != null)
                {
                    List<ProductOption> options = (List<ProductOption>)Configuration.GetCurrentSession().CreateQuery("select o from ProductOption o where o.ProductID = " + mProduct.ID.ToString()).List<ProductOption>();
                    foreach (ProductOption prodOption in options)
                    {
                        if (prodOption.OptionType.ID == optionType.ID)
                        {
                            txtValue.Text = prodOption.Value;
                            break;
                        }
                    }
                }

            }
        }

    }
    
    protected void valCategory_ServerValidate(object source, ServerValidateEventArgs args)
    {
        int catId = 0;
        args.IsValid = int.TryParse(fieldSelectedCategoryId.Value, out catId);
    }
    protected void validateUPC_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string query = "select p from Product p where p.WebsiteID = " + mWebsite.ID.ToString() + " and p.UPC = '" + txtUPC.Text + "' and p.State = " + ((int)CMSObjectState.Published).ToString();
        if (mProduct != null)
            query += " and p.ID != " + mProduct.ID;
        Product productExists = (Product)Configuration.GetCurrentSession().CreateQuery(query).UniqueResult();
        if (productExists != null)
        {
            args.IsValid = false;
        }
    }
    protected void lbToggleFurtherInfo_Click(object sender, EventArgs e)
    {

    }

    //  IMPORTANT: This must be public, not protected.  The adapters OnAdapted... event attributes only work if you
    //  equate them to the names of public event delegate methods.
    public void OnTreeSelection(object sender, EventArgs e)
    {
        fieldSelectedCategoryId.Value = tvCategories.SelectedNode.Value;
    }


}
